<?php

/**
 * @filesource Communicates with the Contact control file to know which student
 * data to get and set. It is the only file that has the SQL queries and MySQL
 * connections
 *
 * @copyright 2011 by Dan, Steven, Brice, Mike, and Aaron.  This program is part
 * of Internship 2 Career, which is free software. It comes with absolutely no
 * warranty. You can redistribute or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation (For
 * more information, see <http://www.gnu.org/licenses/).
 *
 * @version March 4, 2011
 *
 * @author Daniel Pepin, Brice Rader and Aaron Jarzombeck
 */
class dbContact {

   static function createTable() {
      //create table contact
      $query = "
            create table contact(
                contactID               int             NOT NULL AUTO_INCREMENT,
                organizationID          int             NULL,
                fname                   varchar(20)     NOT NULL,
                lname                   varchar(20)     NOT NULL,
                email                   varchar(50)	NULL,
                phone                   varchar(13)	NULL,
                ext                     varchar(4)      NULL,
                fax		        varchar(13)     NULL,
                constraint PK_Contact PRIMARY KEY (contactID),
                constraint FK_Contact_Organization FOREIGN KEY (organizationID)
                    references organization (organizationID)
                );
    ";
      connectToDatabase();
      $result = mysql_query($query);
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      mysql_close();
      //Previous query was successful.
      return true;
   }

   /**
    * Gets all the contacts from the database.
    * @return object Returns MySQL data object
    */
   function getAllContacts() {
      $query = "SELECT * FROM contact";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }

      //Query was successful.
      return $result;
   }

   /**
   * Gets all the contact IDs, first names, and last names from the database.
   * @param object $orgID
   * @return object Returns MySQL data object
   */
   public static function getAllName($orgID) {
      $query = "SELECT contactID,fname,lname FROM contact WHERE organizationID='$orgID' ORDER BY fname ASC";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();

	  //If result is false, display error
      if ($result == false) {
         $output = sprintf("%s", mysql_error());
         return false;
      } else {
         return $result;
      }
   }

   /**
   * Gets contact ID
   * @param object $c
   * @return object returns contact ID
   */
   function getContactID($c) {

      $result = mysql_query("SELECT contactID from contact WHERE fname='{$c->getFname()}' AND lname='{$c->getLname()}'");
      if (!$result) {
         return false;
      } else {
         $row = mysql_fetch_row($result);
         return $row['0'];
      }
   }

   /**
   * Gets organization ID
   * @param object $c
   * @return object returns organization ID
   */
   function getOrganizationID($c) {
      $query = "SELECT organizationID FROM contact
        WHERE contactID='$c'";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      //Query was successful.
      return $result;
   }

   /**
   * Gets first name of contact
   * @param object $c
   * @return object returns first name
   */
   function getFname($c) {
      $query = "SELECT fname FROM contact
        WHERE contactID='$c'";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      //Query was successful.
      return $result;
   }

   /**
   * Gets last name of contact
   * @param object $c
   * @return object returns last name
   */
   function getLname($c) {
      $query = "SELECT Lname FROM contact
        WHERE contactID='$c'";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      //Query was successful.
      return $result;
   }

   /**
   * Gets email of contact
   * @param object $c
   */
   function getEmail($c) {
      $query = "SELECT email FROM contact
        WHERE contactID='$c'";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      //Query was successful.
      return $result;
   }

   /**
   * Gets phone number of contact
   * @param object $c
   * @return object returns phone number
   */
   function getPhone($c) {
      $query = "SELECT phone FROM contact
        WHERE contactID='$c'";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      //Query was successful.
      return $result;
   }

   /**
   * Gets Ext number of contact
   * @param object $c
   * @return object returns ext number
   */
   function getExt($c) {
      $query = "SELECT ext FROM contact
        WHERE contactID='$c'";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      //Query was successful.
      return $result;
   }

   /**
   * Gets fax number of contact
   * @param object $c
   * @return object returns fax number
   */
   function getFax($c) {
      $query = "SELECT fax FROM contact
        WHERE contactID='$c'";
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
	  
	  //If result is false, display error
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      //Query was successful.
      return $result;
   }

   /**
    * Updates contact information.
    * @param object $c Class Contact
    * @return int Returns FALSE if there was an error updating, else returns
    * TRUE
    */
   function updateContact($c) {
      if (!($c instanceof Contact)) {
         return false;
      }
      $contactID = $c->getContactID();
      $organizationID = $c->getOrganizationID();
      $fname = $c->getFName();
      $lname = $c->getLName();
      $email = $c->getEmail();
      $phone = $c->getPhone();
      $ext = $c->getExt();
      $fax = $c->getFax();

      if ($organizationID != '') {
         if (!mysql_query("UPDATE contact SET organizationID='$organizationID'
                    WHERE contactID=$contactID"))
            die("Could not update contact with ID = $contactID");
      }
      if ($fname != '') {
         if (!mysql_query("UPDATE contact SET fname='$fname' WHERE
                    contactID=$contactID"))
            die("Could not update contact with ID = $contactID");
      }
      if ($lname != '') {
         if (!mysql_query("UPDATE contact SET lname='$lname' WHERE
                    contactID=$contactID"))
            die("could not update contact with ID = $contactID");
      }
      if ($email != '') {
         if (!mysql_query("UPDATE contact SET email='$email' WHERE
                    contactID=$contactID"))
            die("could not update contact with ID = $contactID");
      }
      if ($phone != '') {
         if (!mysql_query("UPDATE contact SET phone='$phone' WHERE
                    contactID=$contactID"))
            die("could not update contact with ID = $contactID");
      }
      if ($ext != '') {
         if (!mysql_query("UPDATE contact SET ext='$ext' WHERE
                    contactID=$contactID"))
            die("could not update contact with ID = $contactID");
      }
      if ($fax != '') {
         if (!mysql_query("UPDATE contact SET fax='$fax' WHERE
                    contactID=$contactID"))
            die("could not update contact with ID = $contactID");
      }
      return true;
   }

   /**
    * Adds a contact to the database.
    * @param object $c Class Contact
    * @return bool Returns TRUE if query completes successfully.
    */
   static function addContact($c, &$id = null) {
      if (!$c instanceof Contact) {
         echo ("Invalid arguement insertInto ( ) function<br />");
         return false;
      }
      //Compose the INSERT INTO query string. Primary key value is missing.
      //Database server automatically generates a unique ID for the primary
      //key.
      $query = sprintf("INSERT INTO contact VALUES(null, %d, '%s', '%s',
        '%s', '%s', '%s', '%s')", $c->getOrganizationID(), $c->getFname(), $c->getLname(), $c->getEmail(), $c->getPhone(), $c->getExt(), $c->getFax()
      );
      // printf("->Query: %s<br />", $query);
      connectToDatabase();
      $result = mysql_query($query);
      $id = mysql_insert_id();
      mysql_close();
      if ($result == false) {
         echo mysql_error();
         return false;
      }
      //query was successful.
      return true;
   }

   /**
    * Checks to see if the ID exists.
    * @param object $c Class Contact
    * @return int Returns 0 if ID cannot be found, and 1 if ID is found
    */
   function checkID($c) {
      if (!($c instanceof Contact)) {
         return false;
      }
      $contactID = $c->getContactID();
      connectToDatabase();
      if (mysql_num_rows(mysql_query("SELECT * FROM contact WHERE
                contactID=$contactID")) == false) {
         mysql_close();
//nothing existsmysql_num_rows
         return false;
      } else {
         return true;
      }
   }

   /**
    * Gets all the contact information for a contact with a certain ID.
    * @param int $id ID of contact you want to get.
    * @return object Returns 0 if ID does not exist, or a Contact object
    * if it does
    */
   function getContact($contactID) {
      $c = new Contact();
      $result = mysql_query("SELECT * FROM contact WHERE contactID=
                $contactID");
      if (!$result) {
         return false; //id does not exist
      } else {
         $row = mysql_fetch_assoc($result);
         $c->setContactID($contactID);
         $c->setOrganizationID($row['organizationID']);
         $c->setFname($row['fname']);
         $c->setLname($row['lname']);
         $c->setEmail($row['email']);
         $c->setPhone($row['phone']);
         $c->setExt($row['ext']);
         $c->setFax($row['fax']);
         return $c;
      }
   }

   /**
    * Deletes a contact from the database.
    * @param object $c Class Contact
    * @return bool Returns TRUE if contact can be deleted.
    */
   function deleteContact($c) {
      if (!$c instanceof contact) {
         echo ("Invalid argument deleteFrom( ) function<br />");
         return false;
      }

      //Compose the DELETE FROM query string.
      $query = sprintf("DELETE FROM contact WHERE contactID = %d", $c->getContactID()
      );
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();
      if ($result == false) {
         echo mysql_error();
         return false;
      }

      //Query was successful.
      return true;
   }

   /**
   * Gets all fields by ID
   * @param getAllByID $id
   * @return all fields
   */
   public static function getAllByID($id, &$output) {
      $query = sprintf("SELECT organizationID, fname, lname, email, phone, 
            ext, fax  FROM contact WHERE contactID=%d", $id);
      //printf("->Query: %s<br />", $query);
      connectToDatabase();
      $result = mysql_query($query);
      mysql_close();

      if ($result == false) {
         $output = sprintf("%s", mysql_error());
         return false;
      }
      //process result and print out warning or attribute values
      return dbContact::checkForOneInstance($result, $id, $output);
   }

   /**
   * Checks for one instance
   */
   private static function checkForOneInstance($result, $id, &$output) {
      //Local variables are initialized
      $errorStatus = false;

      $howMany = mysql_num_rows($result);
      //printf("-->Found %d instance(s) for donorID=%d.<br />, $howMany, $id);
      switch ($howMany) {
         case 0:
            $output = sprintf("No Contact instance with ID=%d was found.", $id);
            $errorStatus = true;
            break;
         case 1:
            //mysql_fetch() DOES NOT return primary key values
            $output = mysql_fetch_assoc($result);
            $errorStatus = false;
            break;
         default:
            $output = sprintf("There are multiple Contact instances with
                                   ID=%d.", $id);
            $errorStatus = true;
            break;
      }
      return $errorStatus;
   }

}

?>
